import Dialog from '../components/Dialog'

/**
 *
 * 函数调用Dialog打开
 * 使用api.open(title, description, buttons, textAlign) 来弹出Dialog
 * title: 标题 (字符串或者element node)
 * description: 提示内容 (字符串或者 element node)
 * buttons: 按钮数组 [ { label: '', onClick: () => {}, noDestroy } ]
 *    label: 按钮上文字
 *    onClick: 回调函数
 *    noDestroy: bool  表示是否关闭对话框
 * textAlign: 提示内容水平对齐方式(默认left)
 *
 */

let dialogInstance

function getDialogInstance(props) {
  if (dialogInstance) {
    return dialogInstance
  }

  dialogInstance = Dialog.newInstance({
    ...props,
  })

  return dialogInstance
}

function removeDialog() {
  if (dialogInstance) {
    dialogInstance.destroy()
    dialogInstance = null
  }
}

function openDialog(title, description, buttons, textAlign) {
  const newButtons = buttons.map((button) => {
    const MixClickHandle = () => {
      button.onClick()
      if (!button.noDestroy) {
        removeDialog()
      }
    }
    return {
      label: button.label,
      onClick: MixClickHandle,
    }
  })

  const dialog = getDialogInstance({
    title,
    description,
    buttons: newButtons,
    textAlign,
  })

  dialog.open()
}

const api = {
  open(title, description, buttons, textAlign = 'left') {
    openDialog(title, description, buttons, textAlign)
  },
}

export default api
